
package stcu;

import com.nvlled.route.*;
import stcu.robjects.*;
import java.util.*;

public class ServerAuth {

    private ObjectRouter router;
    private Set<String> db;
    private Set<String> session;

    public ServerAuth(ObjectRouter router) {
        this.router = router;
        db = new HashSet<String>();
        session = new HashSet<String>();

        subscribe();
    }

    public void registerUser(String name) {
        db.add(name);
    }

    public boolean isLoggedIn(String id) {
        return session.contains(id);
    }


    private void subscribe() {
        router.subscribe(Login.class, new ObjectReceiver<Login>() {
            public void receive(Login login) {
                String id = login.getUsername();
                if (db.contains(id)) {
                    if (session.contains(id)) {
                        router.deliver(new Login.Status("Already logged in", id), 
                            login.getSourceAddress());
                    } else {
                        router.deliver(new Login.Status("ok", id), 
                            login.getSourceAddress());
                        session.add(id);
                    }
                } else {
                    router.deliver(new Login.Status("Invalid username", id), 
                        login.getSourceAddress());
                }
            }
        });
        router.subscribe(Logout.class, new ObjectReceiver<Logout>() {
            public void receive(Logout logout) {
                AddressTable table = router.getTable();
                String id = table.getName(logout.getSourceAddress());
                if (session.contains(id)) {
                    session.remove(id);
                }
            }
        });
    }
}

